layui.define(['jquery','form','layer','laytpl','laydate'],function (exports) {
    var $ = layui.jquery,
        layer = layui.layer,
        form = layui.form,
        laydate = layui.laydate;

    var tailoringImg = $('#tailoringImg');
    var tailoringContent = $(".tailoring-content");
    var tailoringcontainer = $(".tailoring-container");

    // ***************** 图片裁剪的js ****************
    //弹出框水平垂直居中
    (window.onresize = function () {
        var win_height = $(window).height();
        var win_width = $(window).width();
        if (win_width <= 512){
            tailoringContent.css({
                "top": (win_height - tailoringContent.outerHeight())/2,
                "left": 0
            });
        }else{
            tailoringContent.css({
                "top": (win_height - tailoringContent.outerHeight())/2,
                "left": (win_width - tailoringContent.outerWidth())/2
            });
        }
    })();

    //cropper图片裁剪
    tailoringImg.cropper({
        aspectRatio: 300/300,//默认比例
        preview: '.previewImg',//预览视图
        guides: false,  //裁剪框的虚线(九宫格)
        autoCropArea: 1,  //0-1之间的数值，定义自动剪裁区域的大小，默认0.8
        dragCrop: true,  //是否允许移除当前的剪裁框，并通过拖动来新建一个剪裁框区域
        movable: true,  //是否允许移动剪裁框
        resizable: true,  //是否允许改变裁剪框的大小
        zoomable: false,  //是否允许缩放图片大小
        mouseWheelZoom: true,  //是否允许通过鼠标滚轮来缩放图片
        touchDragZoom: true,  //是否允许通过触摸移动来缩放图片
        rotatable: true,  //是否允许旋转图片
        crop: function(e) {
            // console.log(e);
            // 输出结果数据裁剪图像。
        }
    });

    // 日期插件渲染
    laydate.render({
        elem: "#birthdate"
    });

    // 地址
    var region = $('#region');
    var region1 = '',
        region2 = '',
        region3 = '';

    $(document).ready(function () {
        // 省数据
        var obj = $('select[name=provinces]');
        getProvinces(0,obj);
    });

    // 省选择
    form.on('select(provinces)',function (data) {
        if(data.value) {
            var title = data.elem[data.elem.selectedIndex].title;
            region1 = title;
            var obj = $('select[name=cities]');
            obj.html('<option value="">请选择市</option>');
            $('select[name=districts]').html('<option value="">请选择县/区</option>');
            getProvinces(data.value,obj);
        }
    });
    // 市选择
    form.on('select(cities)',function (data) {
        if(data.value) {
            var title = data.elem[data.elem.selectedIndex].title;
            region2 = title;
            var obj = $('select[name=districts]');
            obj.html('<option value="">请选择县/区</option>');
            getProvinces(data.value,obj);
        }
    });
    // 区选择
    form.on('select(districts)',function (data) {
        if(data.value) {
            var title = data.elem[data.elem.selectedIndex].title;
            region3 = title;
            region.val(region1 + ' ' + region2 + ' ' + region3);
            userShow.hideDistrict();
        }
    });


    // 获取省市区
    function getProvinces(pid,obj) {
        var obj = obj;
        $.ajax({
            url: "/admin/common/provinces/list",
            type: "post",
            dataType: "json",
            data: {pid:pid},
            success:function (resp) {
                if(resp.code === 0) {
                    var str = '';
                    $.each(resp.data,function (index,value) {
                        str += '<option value="'+value.id+'" title="'+value.name+'">'+value.name+'</option>';
                    })
                    obj.append(str);
                    form.render();
                } else {
                    layer.msg(resp.message||"获取数据失败，请重新加载");
                }
            },
            error:function (resp) {
                layer.msg("服务器繁忙，请稍后再试");
            }
        });
    }

    // 表单验证
    form.verify({
        account:function (value, item) {
            if(!new RegExp("^[a-zA-Z0-9_\u4e00-\u9fa5\\s·]+$").test(value)){
                return '用户名不能有特殊字符';
            }
            if(/(^\_)|(\__)|(\_+$)/.test(value)){
                return '用户名首尾不能出现下划线\'_\'';
            }
            if(/^\d+\d+\d$/.test(value)){
                return '用户名不能全为数字';
            }
        },
        password:[ /^[\S]{6,12}$/,'密码必须6到12位，且不能出现空格'],
        myphone:[/(^$)|^1[34578]\d{9}$/,'请输入正确的手机号'],
        myemail:[/(^$)|^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/,'邮箱格式不正确'],
    });

    // 添加数据
    form.on('submit(save)', function (data) {
        var datas = data.field;
        var index = layer.load(1);
        $.ajax({
            type: "post",
            url: "save",
            dataType: "json",
            data:datas,
            success:function (resp) {
                layer.close(index);
                if(resp.code > 0) {
                    layer.msg(resp.message || '操作失败');
                } else {
                    layer.msg(resp.message || '操作成功');
                    return true;
                }
            },
            error:function (resp) {
                layer.close(index);
                layer.msg(resp.message || '服务繁忙');
            }
        });
        return false;
    });

    // 更新数据
    form.on('submit(update)', function (data) {
        var datas = data.field;
        var index = layer.load(1);
        $.ajax({
            type: "post",
            url: "update",
            dataType: "json",
            data:datas,
            success:function (resp) {
                layer.close(index);
                if(resp.code > 0) {
                    layer.msg(resp.message || '操作失败');
                } else {
                    layer.msg(resp.message || '操作成功');
                    return true;
                }
            },
            error:function (resp) {
                layer.close(index);
                layer.msg(resp.message || '服务繁忙');
            }
        });
        return false;
    });

    // 截图换向判断
    var flagX = true;

    var userShow = {
        // 弹出图片裁剪框
        tailorContainer:function () {
            tailoringcontainer.css('display','block');
        },
        // 图像上传
        selectImg:function (file) {
            if (!file.files || !file.files[0]){
                return;
            }
            var reader = new FileReader();
            reader.onload = function (evt) {
                var replaceSrc = evt.target.result;
                //更换cropper的图片
                $('#tailoringImg').cropper('replace', replaceSrc,false);//默认false，适应高度，不失真
            }
            reader.readAsDataURL(file.files[0]);
        },
        // 旋转
        rotateImg:function () {
            tailoringImg.cropper("rotate", 90);
        },
        // 复位
        resetImg:function () {
            tailoringImg.cropper("reset");
        },
        // 换向
        cropperScaleX:function () {
            if(flagX){
                tailoringImg.cropper("scaleX", -1);
                flagX = false;
            }else{
                tailoringImg.cropper("scaleX", 1);
                flagX = true;
            }
            flagX != flagX;
        },
        // 裁剪后的处理
        sureCut:function () {
            if (tailoringImg.attr("src") == null ){
                layer.msg('请先选择图片',2);
                return false;
            }else{
                var cas = tailoringImg.cropper('getCroppedCanvas');//获取被裁剪后的canvas
                var base64url = cas.toDataURL('image/png'); //转换为base64地址形式
                userShow.putb64(base64url);
                userShow.closeTailor();
            }
        },
        // 关闭裁剪框
        closeTailor:function () {
            tailoringcontainer.toggle();
        },
        // 上传裁剪的图片
        putb64:function (base64url) {
            $('#srcimgurl').attr('src',base64url);
            $('#pnaCoverPic').val(base64url);
        },
        // 地址选择
        showDistrict:function () {
            $('#addressText').css('display','none');
            $('#addressSelect').css('display','block');
        },
        hideDistrict:function () {
            $('#addressText').css('display','block');
            $('#addressSelect').css('display','none');
        },
        // 开放修改密码
        editPass:function () {
            $('#password').removeAttr('disabled').focus();
        }
    };

    exports('userShow',userShow);
});